package org.jeecg.modules.business.service.impl;

import cn.hutool.core.date.DateTime;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.business.dto.CouponsGenerateDto;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.mapper.BusMarketCouponsMapper;
import org.jeecg.modules.business.mapper.BusMarketMemberMapper;
import org.jeecg.modules.business.mapper.BusMemberCardMapper;
import org.jeecg.modules.business.mapper.BusMemberPointLogMapper;
import org.jeecg.modules.business.service.IBusMemberPointLogService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: bus_member_point_log
 * @Author: jeecg-boot
 * @Date:   2023-03-13
 * @Version: V1.0
 */
@Service
public class BusMemberPointLogServiceImpl extends ServiceImpl<BusMemberPointLogMapper, BusMemberPointLog> implements IBusMemberPointLogService {
    @Resource
    private BusMemberCardMapper busMemberCardMapper;

    /**
     * 调整积分
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public  Result savePoint(BusMemberPointLog dto) {
        if (ObjectUtils.isEmpty(dto.getMemberId())) return Result.error("会员id不能为空");
        if (dto.getNum() <= 0) return Result.error("积分数量不能小于1!");
        BusMemberCard member = busMemberCardMapper.selectById(dto.getMemberId());
        if (ObjectUtils.isEmpty(member)) {
            return Result.error("会员不存在");
        }
        Integer balance = 0;
        switch (dto.getType()) {
            case 1:
                balance = member.getIntegral() + dto.getNum();
                break;
            case 2:
                balance = member.getIntegral() - dto.getNum();
                break;
            case 3:
                balance = dto.getNum();
                break;
        }
        if (balance < 0) balance = 0;
        dto.setBalance(balance);
        Boolean res = this.save(dto);
        if (res) {
            member.setIntegral(balance);
            busMemberCardMapper.updateById(member);
        }
        return Result.ok("创建成功");
    }
}
